import { Controller, Get, Post, Put, Delete, Param, Body, UseGuards } from '@nestjs/common';
import { UserService } from './user.service';
import { User } from './user.entity';
import { CreateUserDto } from './dto/create-user.dto';
import { UpdateUserDto } from './dto/update-user.dto';
import { JwtHttpGuard } from '../auth/jwt-http.guard';

@Controller('user')
@UseGuards(JwtHttpGuard)
export class UserController {
  constructor(private readonly userService: UserService) {}

  @Get('list')
  async findAll(): Promise<User[]> {
    return await this.userService.findAll();
  }

  @Get(':id')
  async findOne(@Param('id') id: string): Promise<User | null> {
    return await this.userService.findOne(+id);
  }

  @Post()
  async create(@Body() createUserDto: CreateUserDto): Promise<User> {
    return await this.userService.create(createUserDto);
  }

  @Put(':id')
  async update(@Param('id') id: string, @Body() updateUserDto: UpdateUserDto): Promise<User | null> {
    return await this.userService.update(+id, updateUserDto);
  }

  @Delete(':id')
  async remove(@Param('id') id: string): Promise<void> {
    return await this.userService.remove(+id);
  }

  @Post(':id/roles')
  async assignRole(
    @Param('id') id: string,
    @Body('roleName') roleName: string
  ): Promise<boolean> {
    const user = await this.userService.findOne(+id);
    if (!user) {
      return false;
    }
    return await this.userService.assignRoleToUser(user.username, roleName);
  }

  @Get(':id/roles')
  async getUserRoles(@Param('id') id: string): Promise<string[]> {
    const user = await this.userService.findOne(+id);
    if (!user) {
      return [];
    }
    return await this.userService.getUserRoles(user.username);
  }

  @Post(':id/roles/remove')
  async removeRole(
    @Param('id') id: string,
    @Body('roleName') roleName: string
  ): Promise<boolean> {
    const user = await this.userService.findOne(+id);
    if (!user) {
      return false;
    }
    return await this.userService.removeRoleFromUser(user.username, roleName);
  }
}